package com.ztom.v2;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author ZhangTao
 */
public class Code37MaximumDepthOfBinaryTree {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int maxDepth1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int depth = 0;
        return process(root, depth);
    }

    private int process(TreeNode node, int depth) {
        if (node == null) {
            return depth;
        }
        int l = process(node.left, depth);
        int r = process(node.right, depth);
        return Math.max(l, r) + 1;
    }


    public int maxDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }

        // 这种写法不利于收集每层的数据
        int depth = 0;
        Deque<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int curLevelNodes = 1;
        while (!queue.isEmpty()) {
            TreeNode node = queue.pollFirst();
            if (node.left != null) {
                queue.addLast(node.left);
            }
            if (node.right != null) {
                queue.addLast(node.right);
            }
            if (--curLevelNodes == 0) {
                // 赋值下一层的节点数
                curLevelNodes = queue.size();
                // 当前层结束
                depth++;
            }
        }
        return depth;
    }

    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int depth = 0;
        Deque<TreeNode> queue = new LinkedList<>();
        queue.addLast(root);
        while (!queue.isEmpty()) {
            int curLevelNodes = queue.size();
            // 每层集中一起处理, 可以收集每层的数据
            while (curLevelNodes-- > 0) {
                TreeNode node = queue.pollFirst();
                if (node == null) {
                    continue;
                }
                // 入队下一层的节点
                if (node.left != null) {
                    queue.addLast(node.left);
                }
                if (node.right != null) {
                    queue.addLast(node.right);
                }
            }
            depth++;
        }
        return depth;
    }
}
